package com.sparrow.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.sparrow.filter.StopFilter;
import com.sparrow.manage.util.FileStore;
import com.sparrow.resolver.CustomTemplateResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.TemplateResolver;

import javax.servlet.MultipartConfigElement;
import java.util.HashSet;
import java.util.Set;

/**
 * 配置SpringBoot静态资源目录
 */
@Configuration
public class MvcConfigure extends WebMvcConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(MvcConfigure.class);

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        logger.info("自定义静态配置路径");

        // /manage/** --> classpath: /manageres/
        registry.addResourceHandler(EnvironmentVariables.MANAGE_ACCESS_PREFIX + "/**")
                .addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/manageres/");

        // /preview/** --> file:
        registry.addResourceHandler(EnvironmentVariables.PREVIEW_ACCESS_PREFIX + "/**")
                .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + EnvironmentVariables.getPortalStaticPublishPath());

        // /public/** --> file:resouces/FrogFile/
        registry.addResourceHandler("/" + EnvironmentVariables.FILE_ACCESS_PREFIX + "/**")
                .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + EnvironmentVariables.FILE_RESOURCE_ROOT + "/" + FileStore.STORE_FOLDER + "/");

        // /** --> file:resources/portal/
        registry.addResourceHandler("/**")
                .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + EnvironmentVariables.getPortalStaticPublishPath());

        // /** --> file:resources/portal/
        registry.addResourceHandler("/**/*.html")
                .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + EnvironmentVariables.getPortalStaticPublishPath())
                .setCachePeriod(120);   // 缓存时间2分钟


        super.addResourceHandlers(registry);
    }

    /**
     * 网站关停服务过滤器
     */
    @Bean
    @ConditionalOnProperty(name = "sparrow.stop.enabled", havingValue = "true")
    public FilterRegistrationBean registStopFilter(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        StopFilter stopFilter = new StopFilter();
        registration.setFilter(stopFilter);
        registration.setOrder(1);
        return registration;
    }

    /**
     * 自定义视图解析器
     */
    @Bean
    public TemplateResolver customTemplateResolver(ThymeleafProperties properties){
        CustomTemplateResolver resolver = new CustomTemplateResolver();
        resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
        resolver.setCacheable(properties.isCache());
        resolver.setSuffix(properties.getSuffix());
        if (properties.getEncoding() != null) {
            resolver.setCharacterEncoding(properties.getEncoding().name());
        }
        resolver.setTemplateMode(properties.getMode());
        resolver.setPrefix(ResourceUtils.CLASSPATH_URL_PREFIX + EnvironmentVariables.MANAGE_VIEW_PREFIX);   // 默认模板资源路径

        resolver.addTemplatePathMap(EnvironmentVariables.PREVIEW_VIEW_TEMPLATE, ResourceUtils.FILE_URL_PREFIX + EnvironmentVariables.FILE_RESOURCE_ROOT + "/" + EnvironmentVariables.STATIC_TEMPLATE_STORE_PATH);
        return resolver;
    }

    /**
     * 文件上传配置
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大
        factory.setMaxFileSize("80MB"); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }


    /**
     * 注册thymeleaf的shiro标签
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

    /**
     * 配置thymeleaf支持shiro标签
     */
    @Bean
    public SpringTemplateEngine templateEngine(ShiroDialect shiroDialect, @Qualifier("customTemplateResolver") TemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        Set<IDialect> additionalDialects = new HashSet<>();
        additionalDialects.add(shiroDialect);
        templateEngine.setAdditionalDialects(additionalDialects);
        return templateEngine;
    }


}
